
-- organization definition & meta functions

organization = {}
AllOrgs = {}
organization.__type = "Organization"

organization.GetAll = function()
	return AllOrgs
end

function organization:New()

	if hook.Call( "OrgCreated", { }, self ) == false then
		return
	end

	local obj = {}
	local meta = {
		__index = self
	}
	obj.members = {}
	setmetatable( obj, meta )
	table.insert( AllOrgs, obj )
	
	return obj
	
end

function organization:SetLeader( ply )
	if hook.Call( "NewOrgLeader", { }, ply, self ) == false then return end
	self.leader = ply
	local RF = RecipientFilter()
	for k, v in pairs( self.members ) do
		v:ChatPrint( ply:Nick().." is now the organization's leader." )
		RF:AddPlayer( v )
	end
	umsg.Start( "Neworgleader", RF )
		umsg.Entity( ply )
	umsg.End()
end

function organization:GetLeader()
	return self.leader
end

function organization:GetMembers()
	return self.members
end

function organization:AddMember( ply )
	if !ply:IsPlayer() then return false end
	if !ply:IsValid() then return false end
	if hook.Call( "PlayerJoinedOrg", { }, ply, self ) == false then return end
	for k, v in pairs( organization.GetAll() ) do
		for k2, v2 in pairs( v.members ) do
			if v2 == ply then
				v:RemoveMember( ply )
			end
		end
	end
	for k, v in pairs( self.members ) do
		if ply == v then return end
	end
	for k, v in pairs( self.members ) do
		umsg.Start( "Joinedorg", ply )
			umsg.Entity( v )
		umsg.End()
	end
	table.insert( self.members, ply )
	local RF = RecipientFilter()
	for k, v in pairs( self.members ) do
		v:ChatPrint( ply:Nick().." has joined the organization." )
		RF:AddPlayer( v )
	end
	umsg.Start( "Joinedorg", RF )
		umsg.Entity( ply )
	umsg.End()
	umsg.Start( "Neworgleader", ply )
		umsg.Entity( self.leader )
	umsg.End()
	return self.members
end

function organization:RemoveMember( ply )
	if hook.Call( "PlayerLeftOrg", { }, ply, self ) == false then return end
	if ply == self.leader then self.leader = nil end
	for k, v in pairs( self.members ) do
		if v == ply then
			local RF = RecipientFilter()
			for k2, v2 in pairs( self.members ) do
				v2:ChatPrint( ply:Nick().." has left the organization." )
				RF:AddPlayer( v2 )
			end
			umsg.Start( "Leftorg", RF )
				umsg.Entity( ply )
			umsg.End()
		end
		umsg.Start( "Leftorg", ply )
			umsg.Entity( v )
		umsg.End()
	end
	for k, v in pairs( self.members ) do
		if v == ply then
			table.remove( self.members, k )
		end
	end
end

function organization:SetSpawn( pos, arg, arg )

	self.spawn = pos

end

function organization:GetSpawn()

	return self.spawn
	
end

setmetatable( organization, {__call = organization.New } )
